package com.neusoft.neuiotms.dcam.fixed.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityNotFoundException;
import javax.transaction.Transactional;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import com.neusoft.bizcore.web.bean.TreeBean;
import com.neusoft.bizcore.web.constant.ExceptionConstants;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.bizcore.web.utils.BuildTreeUtil;
import com.neusoft.neuiotms.dcam.fixed.converter.AssetTypeConverter;
import com.neusoft.neuiotms.dcam.fixed.dto.AssetTypeDTO;
import com.neusoft.neuiotms.dcam.fixed.dto.ProductDTO;
import com.neusoft.neuiotms.dcam.fixed.model.Asset;
import com.neusoft.neuiotms.dcam.fixed.model.AssetType;
import com.neusoft.neuiotms.dcam.fixed.repository.AssetRepository;
import com.neusoft.neuiotms.dcam.fixed.repository.AssetTypeRepository;
import com.neusoft.neuiotms.dcam.fixed.service.AssetService;
import com.neusoft.neuiotms.dcam.fixed.service.AssetTypeService;
import com.neusoft.neuiotms.dcam.fixed.service.ProductService;

@Service
public class AssetTypeServiceImpl implements AssetTypeService {

    @Autowired
    private AssetTypeRepository assetTypeRepository;

    @Autowired
    private AssetRepository assetRepository;

    @Autowired
    private AssetTypeConverter assetTypeConverter;

    @Autowired
    private ProductService productService;

    @Autowired
    private AssetService assetService;

    @Override
    public List<AssetTypeDTO> findAll() {
        final List<AssetType> assetType = this.assetTypeRepository.findAll();
        return this.assetTypeConverter.toListDTO(assetType);
    }

    @Override
    public Page<AssetTypeDTO> search(final Pageable pageable, final Searchable searchable) {
        final Page<AssetType> models = this.assetTypeRepository.search(pageable, searchable);
        return this.assetTypeConverter.toPageDTO(models);
    }

    @Override
    public AssetTypeDTO details(final Long id) {
        final AssetType model;
        try {
            model = this.assetTypeRepository.getOne(id);
        } catch (final EntityNotFoundException e) {
            throw new UnitedException("资产类型不存在!", new Object[] {id });
        }
        return this.assetTypeConverter.toDTO(model);
    }

    @Override
    @Transactional
    public AssetTypeDTO create(final AssetTypeDTO dto) {
        final AssetType assetType = this.assetTypeRepository.findByCode(dto.getCode());
        if (assetType != null) {
            throw new UnitedException("类型编码已存在", new Object[] {});
        }

        final AssetType model = this.assetTypeConverter.toModel(dto);
        this.assetTypeRepository.save(model);

        // 资产关系迁移处理
        if (dto.getParentId() != null) {
            final List<AssetType> list = this.assetTypeRepository.findByParentId(dto.getParentId());
            if (CollectionUtils.isNotEmpty(list) && (list.size() == 1)) {
                // final AssetType type = this.assetTypeRepository.getOne(dto.getParentId());
                final List<Asset> assetList = this.assetService.findByType(model.getParent());
                assetList.stream().forEach(l -> {
                    l.setType(model);
                });
                this.assetRepository.saveAll(assetList);
            }
        }

        return this.assetTypeConverter.toDTO(model);
    }

    @Override
    public AssetTypeDTO update(final Long id, final AssetTypeDTO dto) {

        final AssetType assetType = this.assetTypeRepository.findByCode(dto.getCode());
        if ((assetType != null) && (!assetType.getId().equals(id))) {
            throw new UnitedException("类型编码已存在", new Object[] {});
        }

        AssetType model;
        try {
            model = this.assetTypeRepository.getOne(id);
        } catch (final EntityNotFoundException e) {
            throw new UnitedException("资产类型不存在!", new Object[] {id });
        }

        dto.setId(model.getId());
        model = this.assetTypeConverter.toModel(dto);
        this.assetTypeRepository.save(model);
        return this.assetTypeConverter.toDTO(model);
    }

    @Override
    public void delete(final Long id) {
        final AssetType model;
        try {
            model = this.assetTypeRepository.getOne(id);
        } catch (final EmptyResultDataAccessException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {id });
        }

        final List<AssetType> models = this.assetTypeRepository.findByParentId(model.getId());

        if ((models != null) && !models.isEmpty()) {
            throw new UnitedException("该类型存在下级类型，请先删除下级类型", new Object[] {id });
        }

        final List<ProductDTO> productList = this.productService.findByAssetType(model);
        if ((productList != null) && !productList.isEmpty()) {
            throw new UnitedException("该类型下已有产品，请先删除产品", new Object[] {id });
        }

        final List<Asset> assetList = this.assetService.findByType(model);
        if ((assetList != null) && !assetList.isEmpty()) {
            throw new UnitedException("该类型下已有资产，请先删除资产", new Object[] {id });
        }

        try {
            this.assetTypeRepository.deleteById(id);
        } catch (final EmptyResultDataAccessException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {id });
        }
    }

    @Override
    public List<TreeBean> tree() {
        final Sort sort = new Sort(Direction.ASC, "sort");
        final List<AssetType> assetType = this.assetTypeRepository.findAll(sort);
        final List<TreeBean> tree = new ArrayList<>();
        assetType.forEach(type -> {
            final TreeBean bean = new TreeBean();
            bean.setCode(type.getCode());
            bean.setTitle(type.getName());
            final Map<String, Object> attr = new HashMap<>();
            attr.put("id", type.getId());
            attr.put("parentId", type.getParent() == null ? "-1" : type.getParent().getId());
            attr.put("sort", type.getSort());
            attr.put("measureUnit", type.getMeasureUnit());
            bean.setAttr(attr);
            tree.add(bean);
        });
        return new BuildTreeUtil(tree).buildTree();
    }

}
